package org.arch_learn.servlet_container.components.connector;

import io.netty.handler.codec.http.*;
import org.arch_learn.servlet_container.components.Mapper;
import org.arch_learn.servlet_container.components.connector.adapters.ServletRequestAdapter;
import org.arch_learn.servlet_container.components.connector.adapters.ServletResponseAdapter;
import org.arch_learn.servlet_container.pojo.CustomHttpServletRequest;
import org.arch_learn.servlet_container.pojo.CustomHttpServletResponse;

import javax.servlet.http.HttpServlet;
import java.io.RandomAccessFile;

public class Connector {
    private Endpoint endpoint;

    public Connector(Endpoint endpoint) {
        this.endpoint = endpoint;
    }

    public void handleNettyHttpRequest(HttpRequest nettyHttpRequest) {
        //适配器将内部请求对象适配成servlet请求
        CustomHttpServletRequest httpServletRequest = ServletRequestAdapter.getHttpServletRequest(nettyHttpRequest);
        //mapper将servlet请求mapping到对应servlet
        HttpServlet servlet = Mapper.getMappedServlet(this.endpoint.getService(), httpServletRequest);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        try {
            if (servlet != null) {
                //servlet处理请求
                CustomHttpServletResponse httpServletResponse = new CustomHttpServletResponse();
                servlet.service(httpServletRequest, httpServletResponse);
                response = ServletResponseAdapter.adaptHttpServletResponseToNetty(httpServletResponse, response);
                endpoint.write(response);
            } else {
                RandomAccessFile randomAccessFile = ServletResponseAdapter.getNettyReadFileResponse(this.endpoint.getService(), nettyHttpRequest, response);
                endpoint.writeFile(response, randomAccessFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
